﻿using System;
using System.Collections.Generic;
using IssueIT.WebUI.Infrastructure.Helpers;
using IssueIT.WebUI.Models;

namespace IssueIT.WebUI.Infrastructure
{
	public class ImageSettings
	{
		private readonly ImageSizeList _imageSizes = new ImageSizeList();

		public string ImageDataDir { get; private set; }
		public string CacheDir { get; private set; }
		public string ImageUploadDir { get; private set; }

		public ImageSettings()
		{
			ImageDataDir = GetFormattedDir(ConfigHelper.GetSetting("ImageSettings.BaseDir", @"|DataDirectory|\Images\"));
			ImageUploadDir = GetFormattedDir(ConfigHelper.GetSetting("ImageSettings.UploadDir", @"|DataDirectory|\ImageUpload\"));
			CacheDir = GetFormattedDir(ConfigHelper.GetSetting("ImageSettings.CacheDir", @"|DataDirectory|\ImageCache\"));

			LoadBaseImageSizes();
		}

		private static string GetFormattedDir(string baseTemplateDir)
		{
			if( !baseTemplateDir.StartsWith("|DataDirectory|", StringComparison.Ordinal) )
			{
				return baseTemplateDir;
			}

			var appDataDir = AppDomain.CurrentDomain.GetData("DataDirectory") as string;

			if( appDataDir==null )
			{
				throw new NullReferenceException();
			}

			return baseTemplateDir.Replace("|DataDirectory|", appDataDir);
		}

		//todo: load theme imageSizes 
		private void LoadBaseImageSizes()
		{
			const string imageSizebaseKey = "ImageSizes";
			string[] keys = ConfigHelper.GetSetting<string>(imageSizebaseKey).Split(',');

			foreach(var counter in keys)
			{
				var fullKeyForImageSize = string.Concat(imageSizebaseKey, ".", counter);
				var size = LoadNamedImageSetting(fullKeyForImageSize);
				_imageSizes.AddImageSize(counter, size);
			}
		}

		private static ImageSize LoadNamedImageSetting(string keyName)
		{
			var width = ConfigHelper.GetSetting(string.Concat(keyName, ".Width"), 0);
			var height = ConfigHelper.GetSetting(string.Concat(keyName, ".Height"), 0);
			return new ImageSize(width, height);
		}

		public ImageSize GetImageSize(string sizeName)
		{
			return _imageSizes.FindByName(sizeName);
		}

		public IEnumerable<string> GetImageSizeNames()
		{
			return _imageSizes.GetNames();
		}
	}
}